package com.acheli.registry.network.packet;

import com.acheli.ACHeli;
import com.acheli.registry.network.ACHMessages;
import com.acheli.registry.network.ACHeliPacketType;
import com.acheli.registry.network.ICustomSyncable;
import com.acheli.rideable.entites.ComponentEntity;
import com.acheli.rideable.entites.RideableEntity;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.Entity;
import net.minecraftforge.network.NetworkDirection;
import net.minecraftforge.network.NetworkEvent;
import net.minecraftforge.network.PacketDistributor;
import net.minecraftforge.network.simple.SimpleChannel;

import java.util.UUID;
import java.util.function.Supplier;

import static com.acheli.registry.entity.ACHEntities.RIDEABLE_COMPONENT_ENTITY_TYPE;

public class CustomSyncableC2SPacket {
    // 添加字符串字段
    private final CompoundTag tag;

    // 从字节缓冲区解码
    public CustomSyncableC2SPacket(FriendlyByteBuf buf) {
        this.tag = buf.readNbt();
    }

    public CustomSyncableC2SPacket(int originId, UUID senderUUID, CompoundTag data, ACHeliPacketType packetType) {
        tag = data;
        tag.putInt("originId", originId);
        tag.putUUID("senderUUID", senderUUID);
        tag.putString("packetType", packetType.name());
    }

    // 编码到字节缓冲区
    public void toBytes(FriendlyByteBuf buf) {
        buf.writeNbt(tag);
    }

    private boolean handle(Supplier<NetworkEvent.Context> supplier) {
        UUID senderUUID = tag.getUUID("senderUUID");
        NetworkEvent.Context context = supplier.get();
        context.enqueueWork(() -> {
            ServerPlayer player = context.getSender();
            if (player != null) {
                ServerLevel level = player.serverLevel();
                if  (level.getEntity(senderUUID) instanceof ICustomSyncable syncable) {
                    ACHeliPacketType packetType = ACHeliPacketType.valueOf(tag.getString("packetType"));
                    CompoundTag serverTag = syncable.serverReceiveAndSending(tag, player, packetType);
                    CustomSyncableS2CPacket packet = new CustomSyncableS2CPacket(((Entity)syncable).getId(), serverTag, packetType);
                    ACHMessages.CHANNEL.send(
                            PacketDistributor.ALL.noArg(),
                            packet
                    ); // 广播给所有追踪该RideableEntity的玩家

                }

            }
        });
        return true;
    }

    public static void register(SimpleChannel channel) {
        channel.messageBuilder(CustomSyncableC2SPacket.class, ACHMessages.id(), NetworkDirection.PLAY_TO_SERVER)
                .decoder(CustomSyncableC2SPacket::new)
                .encoder(CustomSyncableC2SPacket::toBytes)
                .consumerMainThread(CustomSyncableC2SPacket::handle)
                .add();
    }
}